<?php

namespace App\Admin\Controllers;

use App\Models\Address;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AddressController extends AdminController
{
    /**
     * 获取所有省份列表
     *
     * @return JsonResponse
     */
    public function provinces(): JsonResponse
    {
        try {
            $provinces = Address::getProvinces();
            
            $data = $provinces->map(function ($province) {
                return [
                    'id' => $province->id,
                    'name' => $province->areaname,
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取省份列表失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 根据省份ID获取城市列表
     *
     * @param int $provinceId
     * @return JsonResponse
     */
    public function cities(int $provinceId): JsonResponse
    {
        try {
            $cities = Address::getCities($provinceId);
            
            $data = $cities->map(function ($city) {
                return [
                    'id' => $city->id,
                    'name' => $city->areaname,
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取城市列表失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 根据城市ID获取区县列表
     *
     * @param int $cityId
     * @return JsonResponse
     */
    public function districts(int $cityId): JsonResponse
    {
        try {
            $districts = Address::getDistricts($cityId);
            
            $data = $districts->map(function ($district) {
                return [
                    'id' => $district->id,
                    'name' => $district->areaname,
                ];
            });

            return response()->json([
                'status' => 'success',
                'data' => $data
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => '获取区县列表失败：' . $e->getMessage()
            ], 500);
        }
    }
}